package com.cqhilink.iot.jobstandardmanagement.common.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/2/15.
 */
public class ThreadPoolUtil {
    // 线程池中默认线程的个数为5
    private final int worker_num = 5;
    // 线程池
    private ExecutorService executorService = null;
    //初始化对象
    private static ThreadPoolUtil threadPoolUtil;

    //实例化线程池对象调用
    public synchronized static ThreadPoolUtil getInit() {
        if (threadPoolUtil == null) {
            threadPoolUtil = new ThreadPoolUtil();
            threadPoolUtil.getNewFixedThreadPool(0);
        }
        return threadPoolUtil;
    }

    //创建线程队列
    public synchronized void getNewFixedThreadPool(int num) {
        if (num <= 0) {
            num = worker_num;
        }
        if (executorService == null) {
            executorService = Executors.newFixedThreadPool(num);
        }
    }

    //线程放入
    public synchronized void execute(Runnable runnable) throws Exception {
        if (runnable == null)
            throw new NullPointerException();
        executorService.execute(runnable);
//        executorService.awaitTermination(10L, TimeUnit.SECONDS);//阻塞时间，秒
    }

    //停止任务提交，终止线程池
    public synchronized void closeExecute() {
        if (executorService != null) {
            executorService.shutdown();
            threadPoolUtil.getNewFixedThreadPool(0);
        }
    }

    public static void main(String[] args) throws Exception {
//        ThreadPoolUtil t = ThreadPoolUtil.getInit();
        System.out.println("进入");
        for (int i = 0; i < 11; i++) {
            final int index = i;
//            EmployeePool runnable = new EmployeePool();
//            runnable.setNum(i);
//            runnable.setNames("name1");
//            EmployeePool runnable2 = new EmployeePool();
//            runnable2.setNum(i);
//            runnable2.setNames("name2");
//            EmployeePool runnable3 = new EmployeePool();
//            runnable3.setNum(i);
//            runnable3.setNames("name3");
//            ThreadPoolUtil.getInit().execute(runnable);
//            ThreadPoolUtil.getInit().execute(runnable2);
//            ThreadPoolUtil.getInit().execute(runnable3);
        }
//        ThreadPoolUtil.getInit()
//        hreadPoolUtil.getInit().closeExecute();
    }
}
